﻿using System.Net.NetworkInformation;
namespace TPXSDK.NET.Share;

public class NetUtils
{
    /// <summary>
    /// 快速判断本机是否能访问公网
    /// </summary>
    public static bool IsOnline(int timeoutMillis = 1000)
    {
        try
        {
            using var ping = new Ping();
            var reply = ping.Send("8.8.8.8", timeoutMillis);
            return reply.Status == IPStatus.Success;
        }
        catch
        {
            return false;   // 没网卡、没路由、被防火墙拦等一律视为离线
        }
    }

    /// <summary>
    /// 快速判断本机是否能访问公网（异步版本）
    /// </summary>
    public static Task<bool> IsOnlineAsync(int timeoutMillis = 1000) => Task.Run(() => IsOnline(timeoutMillis));

    /// <summary>
    /// 异步下载文件，支持进度汇报和取消操作
    /// </summary>
    public static async Task DownloadFileAsync(string url, string savePath, IProgress<double>? progress = null, CancellationToken token = default)
    {
        const int bufferSize = 1024*64;
        using var http = new HttpClient();
        using var resp = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);
        resp.EnsureSuccessStatusCode();

        var totalBytes = resp.Content.Headers.ContentLength ?? -1;
        long receivedBytes = 0;

        await using var contentStream = await resp.Content.ReadAsStreamAsync(token);
        await using var fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize, true);

        var buffer = new byte[bufferSize];
        int bytesRead;
        while ((bytesRead = await contentStream.ReadAsync(buffer, token)) > 0)
        {
            await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), token);
            receivedBytes += bytesRead;
            if (totalBytes > 0)
            {
                progress?.Report((double)receivedBytes / totalBytes * 100);
            }
        }
    }
}

